﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using JustinAngel.MetroBlog.Services.Data;

namespace JustinAngel.MetroBlog.Models
{
    public class JsonComment
    {
        public JsonComment()
        {
        }

        public JsonComment(int id, int blogPost, string name, string text, string gravatar, JsonComment[] comments)
        {
            ID = id;
            BlogPost = blogPost;
            this.name = name;
            this.text = text;
            this.gravatar = gravatar;
            this.comments = comments;
        }

        public int ID { get; set; }

        public int BlogPost { get; set; }

        [Required]
        public string name { get; set; }

        public string text { get; set; }

        public string gravatar { get; set; }

        [ScriptIgnore]
        public string Email { get; set; }

        public JsonComment[] comments { get; set; }  
 
        public static JsonComment FromComment(Comment comment)
        {
            return  new JsonComment(comment.ID, comment.BlogPost.ID, comment.Name, 
                StripHtmlAndAddBreaklines(comment.HTML),
                "http://www.gravatar.com/avatar/" + comment.EmailMD5Hash,
                comment.ChildComments.Select(JsonComment.FromComment).ToArray());
        }

        private static string StripHtmlAndAddBreaklines(string html)
        {
            Regex htmlTagsRegex = new Regex(@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Multiline);
            return htmlTagsRegex.Replace(html, string.Empty)
                                .Replace("\r\n", "<br />")
                                .Replace("\r", "<br />");

        }
    }
}